/*
 * Copyright (c) 2007 Xilinx, Inc.  All rights reserved.
 *
 * Xilinx, Inc.
 * XILINX IS PROVIDING THIS DESIGN, CODE, OR INFORMATION "AS IS" AS A
 * COURTESY TO YOU.  BY PROVIDING THIS DESIGN, CODE, OR INFORMATION AS
 * ONE POSSIBLE   IMPLEMENTATION OF THIS FEATURE, APPLICATION OR
 * STANDARD, XILINX IS MAKING NO REPRESENTATION THAT THIS IMPLEMENTATION
 * IS FREE FROM ANY CLAIMS OF INFRINGEMENT, AND YOU ARE RESPONSIBLE
 * FOR OBTAINING ANY RIGHTS YOU MAY REQUIRE FOR YOUR IMPLEMENTATION.
 * XILINX EXPRESSLY DISCLAIMS ANY WARRANTY WHATSOEVER WITH RESPECT TO
 * THE ADEQUACY OF THE IMPLEMENTATION, INCLUDING BUT NOT LIMITED TO
 * ANY WARRANTIES OR REPRESENTATIONS THAT THIS IMPLEMENTATION IS FREE
 * FROM CLAIMS OF INFRINGEMENT, IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 */

#include <stdio.h>
#include <string.h>
#include "sysctl_config.h"

#include "lwip/err.h"
#include "lwip/udp.h"



static struct udp_pcb *connected_pcb = NULL;
static struct pbuf *pbuf_to_be_sent = NULL;




int udp_transfer_data(char* udp_send_buf, int send_bufsize)
{
	err_t err;
	struct udp_pcb *pcb = connected_pcb;
	static int id;
	int *payload;
	int i;
	
	if (!connected_pcb)
	{
		xil_printf("!connected_pcb\n\r");
		return -1;
	}
	if (!pbuf_to_be_sent)
	{
		xil_printf("no pbuf to send\n\r");
		pbuf_to_be_sent = pbuf_alloc(PBUF_RAW, send_bufsize, PBUF_POOL);
	}
	
	
	if(!pbuf_to_be_sent)
	{
		return -1;
	}


	memcpy(pbuf_to_be_sent->payload, udp_send_buf, send_bufsize);
	pbuf_to_be_sent->len = send_bufsize;

	/* always increment the id */
	payload = (int*)(pbuf_to_be_sent->payload);


	err = udp_send(pcb, pbuf_to_be_sent);
	if (err != ERR_OK)
	{
		xil_printf("Error on udp_send: %d\n\r", err);
		return -1;
	}
	
    xil_printf("*************udp send data****************\n\r");
	return 0;
}


int start_utxperf_application()
{
	struct udp_pcb *pcb;
	struct ip_addr ipaddr;
	err_t err;


	/* create a udp socket */
	pcb = udp_new();
	if (!pcb)
	{
		xil_printf("Error creating PCB. Out of Memory\n\r");
		return -1;
	}

	/* bind local address */
	IP4_ADDR(&ipaddr, NETIF_IP1, NETIF_IP2, NETIF_IP3, NETIF_IP4);
	
	
	if ((err = udp_bind(pcb, &ipaddr, UDP_PORT)) != ERR_OK)
	{
		xil_printf("error on udp_bind: %x\n\r", err);
	}
	
	
	
	IP4_ADDR(&ipaddr, SEND_IP1, SEND_IP2, SEND_IP3, SEND_IP4);


	err = udp_connect(pcb, &ipaddr, UDP_PORT);

	connected_pcb = pcb;
	pbuf_to_be_sent = pbuf_alloc(PBUF_RAW, DATA_BUFSIZE, PBUF_POOL);

	return 0;
}

